package com.echo.im.engin.handler;

import com.alibaba.fastjson2.JSONObject;
import com.echo.im.client.handler.RouteSuccessHandler;
import com.echo.im.common.enums.MessageType;
import com.echo.im.common.model.ack.GroupMessageACKInfo;
import com.echo.im.client.model.IMMessage;
import com.echo.im.common.vo.GroupMessageVO;
import com.echo.im.engin.packet.out.PrivateMessageOutPacket;
import com.echo.im.infrastructure.session.SessionContext;
import org.springframework.stereotype.Component;

/**
 * @author: echo
 * @time: 2024-08-25
 */
@Component
public class MessageACKHandler implements RouteSuccessHandler {

    @Override
    public void handle(IMMessage message) {
        if (message.getSeqId()!=null && message.getData() instanceof GroupMessageVO){
            PrivateMessageOutPacket privateMessageOutPacket = new PrivateMessageOutPacket();
            //当sendId为0时说明是服务器发送的消息
            privateMessageOutPacket.setSendId(0L);
            privateMessageOutPacket.setRecvId(message.getSender().getId());
            privateMessageOutPacket.setType(MessageType.ACK.code());
            //构造ACK包
            GroupMessageACKInfo groupMessageACKInfo = new GroupMessageACKInfo();
            //群聊消息ack要多一个orderId
            groupMessageACKInfo.setOrderId(((GroupMessageVO) message.getData()).getOrderId());
            groupMessageACKInfo.setMessageId(message.getMsgId());
            groupMessageACKInfo.setAckId(message.getSeqId());
            privateMessageOutPacket.setContent(JSONObject.toJSONString(groupMessageACKInfo));
            SessionContext.getChannel().writeAndFlush(privateMessageOutPacket);
        }
    }
}
